package com.tanger.common.utils;

import java.util.Random;

/**
 * @Description 随机生成字符串
 * @Author Hchenbin
 * @Date 2022/8/2 14:27
 * @Version 1.0
 */
public class RandomUtils {

    /**
     * 获取数字随机数
     * @param length
     * @return
     */
    public static String getNumberRandom(int length) {

        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {
            val += String.valueOf(random.nextInt(10));
        }
        return val;
    }

    /**
     * 获取字母随机数
     * @param length
     * @return
     */
    public static String getCharRandom(int length) {

        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {
            //输出是大写字母还是小写字母
            int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
            val += (char)(random.nextInt(26) + temp);
        }
        return val;
    }

    /**
     * 获取字母数字随机数
     * @param length
     * @return
     */
    public static String getStringRandom(int length) {

        String val = "";
        Random random = new Random();
        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {
            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if("char".equalsIgnoreCase(charOrNum)){
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            }else if("num".equalsIgnoreCase(charOrNum)) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }

    public static void main(String... args){
        System.err.println("随机数:"+RandomUtils.getNumberRandom(8));
        System.err.println("随机英文:"+RandomUtils.getCharRandom(8));
        System.err.println("随机英文数字:"+RandomUtils.getStringRandom(8));
    }
}
